<template>
  <el-dialog v-bind="dialog" :visible.sync="dialog.visible" @open="dialogOpen">
    <el-tree :data="treeData" v-bind="tree" @check="treeCheck" />
    <el-button slot="footer" size="small" type="primary" @click="submit">确 认</el-button>
  </el-dialog>
</template>

<script>
import { internetApi } from '@/api/api'

export default {
  props: {},
  data() {
    return {
      //弹窗相关的属性
      dialog: {
        visible: false,
        title: '菜单权限',
        width: '90%',
        closeOnClickModal: false
      },
      treeList: [],
      treeData: [],
      tree: {
        props: {
          children: 'children',
          label: 'name'
        },
        showCheckbox: true,
        nodeKey: 'id',
        ref: 'tree'
      },
      roleId: null, //角色id
      menuIdList: [] //菜单列表权限id
    }
  },
  mounted() {},

  methods: {
    treeCheck(vnode, { checkedKeys, halfCheckedKeys }) {
      const ids = halfCheckedKeys.concat(checkedKeys)
      this.menuIdList = ids
    },
    //提交
    async submit() {
      const { menuIdList, roleId } = this
      await this.$request(internetApi.addRoleMenuPermission, { roleId, menuIdList })
      this.dialog.visible = false
      this.$message.success('操作成功')
    },

    tableUpdate(...arg) {
      return this.$refs.table.update(...arg)
    },
    //弹窗打开之前，获取所需数据
    async open(rowId) {
      this.roleId = rowId
      await Promise.all([this.getMenuList(), this.getRoleMenuPermission()])
      this.dialog.visible = true
    },
    //弹窗打开
    async dialogOpen() {
      this.$nextTick(() => {
        //清空之前选中的
        this.$refs.tree.setCheckedKeys([])
        //设置当前选中的菜单
        this.menuIdList.forEach((item) => {
          this.$refs.tree.setChecked(item, true)
        })
      })
    },

    //获取当前角色已有的权限
    async getRoleMenuPermission() {
      const { data } = await this.$request(internetApi.getRoleMenuPermission, {
        roleId: this.roleId
      })
      this.menuIdList = data
    },
    //获取菜单列表
    async getMenuList() {
      //判断是否加载过菜单列表，如果加载过，就不重复加载
      if (this.treeList.length === 0 && this.treeData.length === 0) {
        const { data } = await this.$request(internetApi.getMenuList)
        this.treeList = data
        this.treeData = this.$utils.arrayToTree(data, { pid: 'parentId', rootId: '0' })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-dialog__wrapper ::v-deep.el-dialog {
  max-width: 500px;
}
</style>
